<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="司机姓名" prop="driverName">
            <el-input v-model="formData.driverName" placeholder="请输入司机姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="用户名称" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="用户密码" prop="password">
            <el-input v-model="formData.password" placeholder="请输入用户密码" show-password type="password" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="驾驶证号" prop="driverLicenseNo">
            <el-input v-model="formData.driverLicenseNo" placeholder="请输入驾驶证号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="驾驶证类型" prop="licenseType">
            <el-select v-model="formData.licenseType" placeholder="请选择驾驶证类型">
              <el-option label="A1" value="A1" />
              <el-option label="A2" value="A2" />
              <el-option label="A3" value="A3" />
              <el-option label="B1" value="B1" />
              <el-option label="B2" value="B2" />
              <el-option label="C1" value="C1" />
              <el-option label="C2" value="C2" />
              <el-option label="C3" value="C3" />
              <el-option label="C4" value="C4" />
              <el-option label="D" value="D" />
              <el-option label="E" value="E" />
              <el-option label="F" value="F" />
              <el-option label="M" value="M" />
              <el-option label="N" value="N" />
              <el-option label="P" value="P" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职时间" prop="hireDate">
            <el-date-picker v-model="formData.hireDate" type="date" placeholder="请选择入职时间" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="formData.status">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作状态">
            <el-radio-group v-model="formData.workStatus">
              <el-radio :label="0">空闲</el-radio>
              <el-radio :label="1">工作中</el-radio>
              <el-radio :label="2">休息</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="身份证正面照片">
            <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload" action="#"
              :http-request="(options) => handleImageUpload(options, 'idCardFrontImg')">
              <img v-if="formData.idCardFrontImg" :src="formData.idCardFrontImg" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证背面照片">
            <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload" action="#"
              :http-request="(options) => handleImageUpload(options, 'idCardBackImg')">
              <img v-if="formData.idCardBackImg" :src="formData.idCardBackImg" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="驾驶证照片">
            <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload" action="#"
              :http-request="(options) => handleImageUpload(options, 'driverLicenseImg')">
              <img v-if="formData.driverLicenseImg" :src="formData.driverLicenseImg" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="OCR识别数据">
            <el-button type="primary" @click="importFromOCR" :disabled="!hasOCRData">从OCR识别结果导入</el-button>
            <el-text v-if="formData.ocrWords" type="success" style="margin-left: 10px;">已导入OCR数据</el-text>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import * as DriverApi from '@/api/system/driver'
import * as FileApi from '@/api/infra/file'
import { FormRules, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadRequestOptions } from 'element-plus'

defineOptions({ name: 'SystemDriverForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  username: '',
  nickname: '',
  password: '',
  driverName: '',
  mobile: '',
  email: '',
  driverLicenseNo: '',
  licenseType: '',
  sex: undefined,
  hireDate: '',
  status: CommonStatusEnum.ENABLE,
  workStatus: 0,
  remark: '',
  idCardFrontImg: '',
  idCardBackImg: '',
  driverLicenseImg: '',
  ocrWords: ''
})
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  driverName: [{ required: true, message: '司机姓名不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  mobile: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  driverLicenseNo: [{ required: true, message: '驾驶证号不能为空', trigger: 'blur' }],
  licenseType: [{ required: true, message: '驾驶证类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DriverApi.getDriver(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DriverApi.DriverVO
    if (formType.value === 'create') {
      await DriverApi.createDriver(data)
      message.success(t('common.createSuccess'))
    } else {
      await DriverApi.updateDriver(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 图片上传前的校验 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    message.error('图片只能是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/** 处理图片上传 */
const handleImageUpload = async (options: UploadRequestOptions, fieldName: string) => {
  let loadingInstance = null
  try {
    console.log('开始图片上传，文件信息:', {
      name: options.file.name,
      size: options.file.size,
      type: options.file.type,
      fieldName
    })

    // 显示上传中状态
    loadingInstance = ElLoading.service({
      text: '图片上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 验证文件对象
    if (!options.file) {
      throw new Error('文件对象为空')
    }

    // 创建FormData对象
    const uploadFormData = new FormData()
    uploadFormData.append('file', options.file)

    console.log('准备调用FileApi.updateFile上传文件')

    // 上传文件到阿里云
    const uploadResponse = await FileApi.updateFile(uploadFormData)

    console.log('FileApi.updateFile响应:', uploadResponse)

    if (!uploadResponse) {
      throw new Error('文件上传API无响应')
    }

    if (!uploadResponse.data) {
      throw new Error('文件上传API响应数据为空')
    }

    const fileUrl = uploadResponse.data.trim()
    console.log('获取到文件URL:', fileUrl)

    // 直接使用上传返回的URL
    formData.value[fieldName] = fileUrl

    message.success('图片上传成功')

  } catch (error) {
    console.error('图片上传失败，详细错误信息:', {
      error,
      message: error?.message || '未知错误',
      stack: error?.stack,
      response: error?.response,
      status: error?.response?.status,
      statusText: error?.response?.statusText,
      data: error?.response?.data
    })

    let errorMessage = '图片上传失败，请重试'

    if (error?.response) {
      // 网络请求有响应但状态码错误
      const status = error.response.status
      const statusText = error.response.statusText
      errorMessage = `上传失败 (${status}): ${statusText}`

      if (error.response.data?.msg) {
        errorMessage = error.response.data.msg
      }
    } else if (error?.message) {
      // 有错误消息
      errorMessage = error.message
    } else if (typeof error === 'string') {
      // 错误是字符串
      errorMessage = error
    }

    message.error(errorMessage)
  } finally {
    // 关闭loading
    if (loadingInstance) {
      loadingInstance.close()
    }
  }
}

/** 检查是否有OCR数据 */
const hasOCRData = computed(() => {
  // 检查localStorage中是否有OCR识别结果
  const ocrResult = localStorage.getItem('ocrRecognizeResult')
  return !!ocrResult
})

/** 从OCR识别结果导入数据 */
const importFromOCR = () => {
  try {
    const ocrResult = localStorage.getItem('ocrRecognizeResult')
    if (!ocrResult) {
      message.warning('没有找到OCR识别结果，请先进行OCR识别')
      return
    }
    
    const ocrData = JSON.parse(ocrResult)
    console.log('导入OCR数据:', ocrData)
    
    // 将OCR words数据存储到表单中
    if (ocrData.words && Array.isArray(ocrData.words)) {
      formData.value.ocrWords = JSON.stringify(ocrData.words)
      message.success('OCR数据导入成功')
    } else {
      message.warning('OCR识别结果格式不正确')
    }
  } catch (error) {
    console.error('导入OCR数据失败:', error)
    message.error('导入OCR数据失败：' + error.message)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    username: '',
    nickname: '',
    password: '',
    driverName: '',
    mobile: '',
    email: '',
    driverLicenseNo: '',
    licenseType: '',
    sex: undefined,
    hireDate: '',
    status: CommonStatusEnum.ENABLE,
    workStatus: 0,
    remark: '',
    idCardFrontImg: '',
    idCardBackImg: '',
    driverLicenseImg: '',
    ocrWords: ''
  }
  formRef.value?.resetFields()
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>
